//
//  ZLLearnSelectionVideoViewController.m
//  ZLExamination
//
//  Created by Zheng on 2017/10/26.
//  Copyright © 2017年 Zheng. All rights reserved.
//

#import "ZLLearnSelectionVideoViewController.h"
#import <WebKit/WebKit.h>
#import "ZLCourseLerningDetailModel.h"
#import "ZLExamBeginExitPromptView.h"
#import "ZLBaseNavigationController.h"
#import "ZLExciseBeginViewController.h"

@interface ZLLearnSelectionVideoViewController () <WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIView *beginExerciseView;
@property (nonatomic, strong) ZLExamBeginExitPromptView *promptView; //退出提示
@property (nonatomic) BOOL isRecord; //是否记录学习时间
@property (nonatomic) NSInteger startTime;

@end

@implementation ZLLearnSelectionVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _startTime = [[NSDate date] timeIntervalSince1970];
    
    self.navigationItem.title = _model.title;
    
    [self.view addSubview:self.webView];
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(230);
    }];
    
    [self clearCache];
    
    [self.view addSubview:self.beginExerciseView];
    
    [_beginExerciseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_webView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(60);
    }];

    [[UIApplication sharedApplication].keyWindow addSubview:self.promptView];

    
    __weak typeof(self) weakSelf = self;
    //提交学习记录
    [_promptView setEnterCallBack:^{
        
        NSInteger minute = [weakSelf getLearnTimeMinute];
        if (minute == 0) {
            weakSelf.isRecord = YES;
            ZLExciseBeginViewController *exciseVC = [[ZLExciseBeginViewController alloc] init];
            exciseVC.model = weakSelf.model;
            ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:exciseVC];
            [weakSelf presentViewController:nav animated:YES completion:nil];
        } else {
            NSString *curriculum_id = weakSelf.model.curriculum_id;
            NSDictionary *param = @{@"curriculum_id":curriculum_id,
                                    @"the_read_time" : @(minute)};
            
            if (!weakSelf.isRecord) {
                [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/stop_curriculum" parameters:param success:^(id response) {
                    if (response[@"error_code"]) {
                        NSLog(@"%@",response[@"error_msg"]);
                    } else {
                        weakSelf.isRecord = YES;
                    }
                } failure:^{
                    NSLog(@"网络或服务器出错");
                }];
            } else {
                ZLExciseBeginViewController *exciseVC = [[ZLExciseBeginViewController alloc] init];
                exciseVC.model = weakSelf.model;
                ZLBaseNavigationController *nav = [[ZLBaseNavigationController alloc] initWithRootViewController:exciseVC];
                [weakSelf presentViewController:nav animated:YES completion:nil];
            }
        }
    }];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    if (!_isRecord) {
        NSInteger minute = [self getLearnTimeMinute];
        if (minute > 0) {
            NSDictionary *param = @{@"curriculum_id":_model.curriculum_id,
                                    @"the_read_time" : @(minute)};
            [[YCRequestDataService sharedManager] Post:@"curriculum/curriculum/stop_curriculum" parameters:param success:^(id response) {
                if (response[@"error_code"]) {
                    NSLog(@"%@",response[@"error_msg"]);
                } else {
                    _isRecord = YES;
                }
            } failure:^{
                NSLog(@"网络或服务器出错");
            }];
        }
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(popToCourseLearningDetail) name:@"kExerciseResultDismissNotification" object:nil];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kExerciseResultDismissNotification" object:nil];
}

- (void)popToCourseLearningDetail {
#pragma mark 练习结果关闭跳转详情
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"kExerciseResultDismissNotification" object:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
    
}


#pragma mark - 清理缓存
- (void)clearCache {
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
        NSSet *websiteDataTypes = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                                        WKWebsiteDataTypeMemoryCache,
                                                        WKWebsiteDataTypeCookies]];
        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
            [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_model.video_url]]];
        }];
    } else {
        NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
        NSError *errors;
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&errors];
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_model.video_url]]];
    }
}

#pragma mark - wkwebview navigationdelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    decisionHandler(WKNavigationActionPolicyAllow);

}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
}

#pragma mark - 子视图
- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame];
        _webView.navigationDelegate = self;
        _webView.configuration.allowsInlineMediaPlayback = YES;
        _webView.backgroundColor = kRGB_COLOR(46, 46, 46, 1);
    }
    return _webView;
}

- (UIView *)beginExerciseView {
    if (!_beginExerciseView) {
        _beginExerciseView = [[UIView alloc] init];
        _beginExerciseView.backgroundColor = kMY_BLUE_COLOR;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.backgroundColor = kMY_BLUE_COLOR;
        [btn setTitle:@"进入练习" forState:UIControlStateNormal];
        [btn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        btn.layer.borderColor = UIColor.whiteColor.CGColor;
        btn.layer.borderWidth = 1;
        btn.titleLabel.font = kMyFont(15);
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        [_beginExerciseView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(-15);
            make.centerY.equalTo(_beginExerciseView);
            make.width.mas_equalTo(90);
            make.height.mas_equalTo(35);
        }];
    }
    return _beginExerciseView;
}

- (ZLExamBeginExitPromptView *)promptView {
    if (!_promptView) {
        _promptView = [[ZLExamBeginExitPromptView alloc] initWithFrame:kSCREEN_BOUNDS];
        _promptView.titleLbl.text = @"是否进入练习";
        _promptView.contentLbl.text = @"进入练习后，将退出学习";
    }
    return _promptView;
}

#pragma mark - 点击事件
#pragma mark 进入练习
- (void)btnAction:(UIButton *)sender {
    [_promptView showExitPromptView];
}


- (NSInteger)getLearnTimeMinute {
    NSInteger second = ([[NSDate date] timeIntervalSince1970] - _startTime);
    if (second < 60 && second >= 30) second = 1;
    NSInteger minute = second/60;
    return minute;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
